<template>
	<view class="page">
		<image src="/static/dingbu.png" class="mine-navbar-bg" :style="{ height: navbarHeight + 'rpx' }"
			mode="aspectFill" />
		<u-navbar title="抽样单" :autoBack="true" leftIconColor="#fff" bgColor="transparent" :titleStyle="{ color: '#fff' }"
			safeAreaInsetTop placeholder />

		<scroll-view scroll-y class="scroll">
			<!-- 基本信息 -->
			<view class="card">
				<view class="card-title">基本信息</view>
				<view class="row-2">
					<view class="form-item required">
						<text class="label">抽样编号</text>
						<u-input v-model="form.simplingCode" placeholder="请输入抽样编号" disabled />
					</view>
					<view class="form-item">
						<text class="label">任务来源</text>
						<u-input v-model="form.taskSource" placeholder="任务来源" disabled />
					</view>
				</view>
				<view class="row-2">
					<view class="form-item required">
						<text class="label"> 监测类别</text>
						<u-input :value="monitorTypeLabel" placeholder="监测类别" disabled />
					</view>
				</view>
			</view>

			<!-- 土壤信息 -->
			<view class="card">
				<view class="card-title">土壤信息</view>
				<view class="row-2">
					<view class="form-item required">
						<text class="label">土壤类型</text>
						<view class="picker-box" @click="onChooseSoilType">{{ soilTypeMap[form.soilType] || '请选择土壤类型' }}</view>
					</view>
					<view class="form-item required">
						<text class="label"> 灌溉方式</text>
						<view class="picker-box" @click="onChooseIrrigate">{{ irrigateTypeMap[form.irrigationMethod] || '请选择灌溉方式' }}</view>
					</view>
				</view>
				<view class="row-2">
					<view class="form-item required">
						<text class="label"> 种植产品</text>
						<view class="picker-box" @click="openSpeciesPicker">{{ form.plantProduct || '请选择种植产品' }}</view>
					</view>
					<view class="form-item">
						<text class="label">周边环境</text>
						<u-input v-model="form.surroundingsData" placeholder="请输入周边环境描述" />
					</view>
				</view>
			</view>

			<!-- 树种选择器（u-picker 两级联动） -->
			<u-picker
				:show="speciesPickerVisible"
				:columns="speciesColumns"
				keyName="label"
				@cancel="speciesPickerVisible=false"
				@close="speciesPickerVisible=false"
				@change="onSpeciesColumnsChange"
				@confirm="onSpeciesPickerConfirm"
			/>

			<!-- 采样信息 -->
			<view class="card">
				<view class="card-title">采样信息</view>
				<view class="row-2">
					<view class="form-item required">
						<text class="label">监测场所</text>
						<u-input v-model="form.monitorPlace" placeholder="请输入监测场所" />
					</view>
					<view class="form-item required">
						<text class="label">采样依据</text>
						<u-input v-model="form.simplingStandard" placeholder="采样依据" />
					</view>
				</view>
				<view class="row-2">
					<view class="form-item required">
						<text class="label">采样深度</text>
						<view class="input-with-unit">
							<u-input v-model="form.simplingDeep" placeholder="请输入深度" />
							<text class="unit">cm</text>
						</view>
					</view>
					<view class="form-item required">
						<text class="label">采样重量</text>
						<view class="input-with-unit">
							<u-input v-model="form.sampleWeight" placeholder="请输入采样重量" />
							<text class="unit">kg</text>
						</view>
					</view>
				</view>
				<view class="row-2">
					<view class="form-item required">
						<text class="label">采样时间</text>
						<u-datetime-picker v-model="dateVisible" :show="dateVisible" mode="date" @confirm="onDateConfirm"
							@cancel="dateVisible=false" />
						<view class="picker-box" @click="dateVisible=true">{{ form.simplingTime || '选择日期' }}</view>
					</view>
					<view class="form-item required">
						<text class="label">采样地点</text>
						<view class="input-with-action">
							<u-input v-model="form.simplingPlace" placeholder="请输入采样地点" />
							<view class="action-btn" @click="searchLocation">检索</view>
						</view>
					</view>
				</view>
				<view class="map-tip">
					<text class="tip-icon">ℹ</text>
					<text class="tip-text">若定位不准，可拖动地图并双击地图中的位置进行手动定位</text>
				</view>
				<view class="map-wrapper">
					<!-- #ifdef H5 -->
					<view id="tiandituMap" class="tianditu-map"></view>
					<!-- #endif -->
					<!-- #ifndef H5 -->
					<map class="tianditu-map" :longitude="Number(form.lng) || Number(defaultLng)" :latitude="Number(form.lat) || Number(defaultLat)" :scale="mapScale" @tap="onNativeMapTap"></map>
					<!-- #endif -->
				</view>
				<view class="row-2">
					<view class="form-item required">
						<text class="label">经度</text>
						<u-input v-model="form.lng" placeholder="经度" />
					</view>
					<view class="form-item required">
						<text class="label">纬度</text>
						<u-input v-model="form.lat" placeholder="纬度" />
					</view>
				</view>
				<view class="form-item required">
					<text class="label">采样人员</text>
					<u-input v-model="form.simplingPerson" placeholder="采样人员" />
				</view>
			</view>

			<!-- 受检方信息 -->
			<view class="card">
				<view class="card-title">受检方信息</view>
				<view class="row-2">
					<view class="form-item required">
						<text class="label">受检单位名称</text>
						<u-input v-model="form.testedName" placeholder="受检单位名称" />
					</view>
					<view class="form-item">
						<text class="label">受检方类型</text>
						<view class="picker-box" @click="onChooseTestedType">{{ form.testedType || '请选择受检方类型' }}</view>
					</view>
				</view>
				<view class="row-2">
					<view class="form-item required">
						<text class="label"> 联系人</text>
						<u-input v-model="form.contact" placeholder="联系人" />
					</view>
					<view class="form-item required">
						<text class="label"> 联系电话</text>
						<u-input v-model="form.contactPhone" placeholder="联系电话" />
					</view>
				</view>
				<view class="row-2">
					<view class="form-item">
						<text class="label">证件号码</text>
						<u-input v-model="form.testedIdNo" placeholder="证件号码" />
					</view>
					<view class="form-item">
						<text class="label">通讯地址</text>
						<u-input v-model="form.address" placeholder="通讯地址" />
					</view>
				</view>
			</view>

			<!-- 备注信息 -->
			<view class="card">
				<view class="card-title">备注信息</view>
				<view class="row-2">
					<view class="form-item">
						<text class="label">采样方备注</text>
						<u-textarea v-model="form.simplingRemark" placeholder="" autoHeight />
					</view>
					<view class="form-item">
						<text class="label">受检方备注</text>
						<u-textarea v-model="form.testedRemark" placeholder="" autoHeight />
					</view>
				</view>
			</view>

			<!-- 附件信息 -->
			<view class="card">
				<view class="card-title">附件信息</view>
				<view class="form-item">
					<text class="label">附件地址</text>
					<uni-file-picker
						mode="list"
						:limit="5"
						:del-icon="true"
						:auto-upload="false"
						:file-extname="attachmentExts"
						:value="attachmentList"
						@select="onAttachmentSelect"
						@delete="onAttachmentDelete"
					></uni-file-picker>
					<text class="hint">支持 doc/docx/xls/xlsx/ppt/pptx/txt/pdf/jpg/jpeg/png，单个文件不超过10MB</text>
				</view>
				<view class="form-item">
					<text class="label">采样人员签名</text>
					<uni-file-picker
						mode="image"
						:limit="1"
						:del-icon="true"
						:auto-upload="false"
						upload-icon="plus"
						:value="samplingSignList"
						@select="onSamplingSignSelect"
						@delete="onSamplingSignDelete"
					></uni-file-picker>
					<text class="hint">支持 jpg/jpeg/png，单张不超过5MB</text>
				</view>
				<view class="form-item">
					<text class="label">受检方签名</text>
					<uni-file-picker
						mode="image"
						:limit="1"
						:del-icon="true"
						:auto-upload="false"
						upload-icon="plus"
						:value="testedSignList"
						@select="onTestedSignSelect"
						@delete="onTestedSignDelete"
					></uni-file-picker>
					<text class="hint">支持 jpg/jpeg/png，单张不超过5MB</text>
				</view>
			</view>

			<view class="safe-space" />
		</scroll-view>

		<view class="footer">
			<view class="btn btn-outline" @click="onCancel">取消</view>
			<view class="btn btn-secondary" @click="onSaveDraft">存草稿</view>
			<view class="btn btn-primary" @click="onSubmit">提交</view>
		</view>
	</view>
</template>

<script>
	import navbarMixin from '@/common/navbarMixin'
	import { trcydetail, editcy, commitSampling } from '@/api/sylin/index.js'
	import { getTreeSpeciesList } from '@/api/economicforest'
	import upload from '@/utils/upload'
	import request from '@/utils/request'
	export default {
		mixins: [navbarMixin],
		data() {
			return {
				id: '',
				taskId: '',
				dateVisible: false,
				submitLoading: false,
				detectionTypeDictType:'product_monitor_type',
				detectionTypeMap:{},
				soilTypeMap: {},
				irrigateTypeMap: {},
				irrigateTypeOptions: [],
				soilTypeOptions: [],
				speciesOptions: [],
				speciesPickerVisible: false,
				speciesColumns: [[], []],
				attachmentList: [],
				samplingSignList: [],
				testedSignList: [],
				attachmentExts: ['doc','docx','xls','xlsx','ppt','pptx','txt','pdf','jpg','jpeg','png'],
				defaultLng: 117.03,
				defaultLat: 36.40,
				mapScale: 12,
				mapInstance: null,
				mapMarker: null,
				mapKey: '',
				isH5: false,
				pendingGrowProductValue: '',
				testedTypeOptions: ['企业','个人','合作社','其他'],
				form: {
					// 基本
					simplingCode: '',
					taskSource: '',
					monitorType: '',
					// 土壤
					soilType: '',
					irrigationMethod: '',
					plantProduct: '',
					growProductPath: [],
					surroundingsData: '',
					// 采样
					monitorPlace: '',
					simplingStandard: '',
					simplingDeep: '',
					sampleWeight: '',
					simplingTime: '',
					simplingPlace: '',
					simplingPerson: '',
					lng: '',
					lat: '',
					// 受检方
					testedName: '',
					testedType: '',
					contact: '',
					contactPhone: '',
					testedIdNo: '',
					address: '',
					// 备注与附件
					simplingRemark: '',
					testedRemark: '',
					simplingSign: '',
					testedSign: '',
					attachment: '',
					attachments: [],
					remark: ''
				}
			}
		},
		onLoad(options) {
			// #ifdef H5
			this.isH5 = true
			// #endif
			this.loadDetectionDict()
			this.loadSoilDict()
			this.loadIrrigateDict()
			this.loadSpeciesList()
			this.loadMapKey()
			
			if (options.id) {
				this.id = options.id
				// 获取taskId参数
				if (options.taskId) {
					this.taskId = options.taskId
				}
				// 如果URL参数中有simplingCode、taskSource、monitorType，直接设置到表单中
				if (options.simplingCode) {
					this.form.simplingCode = decodeURIComponent(options.simplingCode)
				}
				if (options.taskSource) {
					this.form.taskSource = decodeURIComponent(options.taskSource)
				}
				if (options.monitorType) {
					this.form.monitorType = decodeURIComponent(options.monitorType)
				}
				this.loadDetail()
			}
		},
		computed:{
			monitorTypeLabel(){
				const code = this.form.monitorType
				return this.detectionTypeMap[code] || code || ''
			}
		},
		methods: {
			async loadIrrigateDict(){
				try{
					const res = await request({url:`/system/dict/data/type/irrigate_type`,method:'get'})
					const rows = Array.isArray(res)?res:(Array.isArray(res?.data)?res.data:[])
					const map = {}
					const opts = []
					rows.forEach(d=>{const label=d.dictLabel??d.label??d.name;const value=d.dictValue??d.value??d.code;if(value!=null){map[value]=label||value;opts.push({value,label})}})
					this.irrigateTypeMap = map
					this.irrigateTypeOptions = opts
				}catch(e){this.irrigateTypeMap={};this.irrigateTypeOptions=[]}
			},
			async loadSoilDict(){
				try{
					const res = await request({url:`/system/dict/data/type/soil_type`,method:'get'})
					const rows = Array.isArray(res)?res:(Array.isArray(res?.data)?res.data:[])
					const map = {}
					const opts = []
					rows.forEach(d=>{const label=d.dictLabel??d.label??d.name;const value=d.dictValue??d.value??d.code;if(value!=null){map[value]=label||value;opts.push({value,label})}})
					this.soilTypeMap = map
					this.soilTypeOptions = opts
				}catch(e){this.soilTypeMap={};this.soilTypeOptions=[]}
			},
			async loadSpeciesList(){
				let options = []
				try{
					const res = await request({ url: '/forest/species/listAll', method: 'get' })
					const rows = Array.isArray(res?.data) ? res.data : Array.isArray(res) ? res : []
					if (rows.length) {
						options = rows.map(parent => ({
							label: parent.treeSpeciesName || parent.speciesName || parent.label,
							value: parent.treeSpeciesCode || parent.speciesCode || parent.value,
							children: (parent.treeSpecies || parent.children || []).map(child => ({
								label: child.treeSpeciesName || child.speciesName || child.label,
								value: child.treeSpeciesCode || child.speciesCode || child.value
							}))
						}))
					}
				}catch(e){
					// 如果 listAll 接口不存在，则回退到 selectListData
					try{
						const fallback = await getTreeSpeciesList({ pageNum:1, pageSize:9999 })
						const rows = Array.isArray(fallback?.data) ? fallback.data : Array.isArray(fallback) ? fallback : []
						options = rows.map(item => ({
							label: item.speciesName || item.treeSpeciesName || item.label,
							value: item.speciesCode || item.treeSpeciesCode || item.value
						}))
					}catch(err){
						options = []
					}
				}
				this.speciesOptions = options
				// 初始化 u-picker 两级列
				const parents = options.map(o=>({ label: o.label, value: o.value }))
				const children = (options[0]?.children || []).map(c=>({ label: c.label, value: c.value }))
				this.speciesColumns = [parents, children]
				this.applyGrowProductValue()
			},
			onChooseIrrigate(){
				const items = this.irrigateTypeOptions.map(o=>o.label||o.value)
				uni.showActionSheet({
					itemList: items,
					success: (res)=>{
						const idx = res.tapIndex
							if (idx!=null && this.irrigateTypeOptions[idx]){
								this.form.irrigationMethod = this.irrigateTypeOptions[idx].value
							}
					}
				})
			},
			openSpeciesPicker(){
				if(!this.speciesOptions.length){
					uni.showToast({ title: '树种数据未加载', icon: 'none' })
					return
				}
				this.speciesPickerVisible = true
			},
			onSpeciesConfirm({ value, label }){
				this.speciesPickerVisible = false
				if(!value || !value.length){
					return
				}
				this.form.growProductPath = value
				const displayLabel = Array.isArray(label) ? label[label.length - 1] : label
				this.form.plantProduct = displayLabel || ''
				this.tryGenerateSimplingCode(value[value.length - 1])
			},
			onSpeciesColumnsChange(e){
				const { columnIndex, index } = e
				if(columnIndex === 0){
					const parent = this.speciesOptions[index]
					const children = (parent?.children || []).map(c=>({ label: c.label, value: c.value }))
					this.speciesColumns.splice(1, 1, children)
				}
			},
			onSpeciesPickerConfirm(e){
				// u-picker confirm 回调，e.value 为选中的项数组
				const items = e?.value || []
				const values = items.map(i=>i?.value).filter(Boolean)
				const labels = items.map(i=>i?.label).filter(Boolean)
				this.onSpeciesConfirm({ value: values, label: labels })
			},
			applyGrowProductValue(){
				if(!this.pendingGrowProductValue){
					return
				}
				const value = this.pendingGrowProductValue
				for(const parent of this.speciesOptions){
					if(parent.value === value){
						this.form.growProductPath = [parent.value]
						this.form.plantProduct = parent.label
						this.pendingGrowProductValue = ''
						return
					}
					if(Array.isArray(parent.children)){
						for(const child of parent.children){
							if(child.value === value){
								this.form.growProductPath = [parent.value, child.value]
								this.form.plantProduct = child.label
								this.pendingGrowProductValue = ''
								return
							}
						}
					}
				}
				if(!this.form.plantProduct && this.pendingGrowProductValue){
					this.form.plantProduct = this.pendingGrowProductValue
				}
				this.pendingGrowProductValue = ''
			},
			async tryGenerateSimplingCode(code){
				if(!code){
					return
				}
				try{
					const res = await request({
						url: '/forest/syl/soil/createSimplingCode',
						method: 'get',
						params: {
							speciesCode: code,
							id: this.id,
							simplingCode: this.form.simplingCode
						}
					})
					const newCode = res?.msg || res?.data?.simplingCode || res?.data || ''
					if(typeof newCode === 'string' && newCode){
						this.form.simplingCode = newCode
					}
				}catch(e){
					console.warn('生成抽样编号失败', e)
				}
			},
			updateAttachmentFromData(){
				const collected = new Set()
				const addValue = (val)=>{
					if(val){
						val.split(',').forEach(item=>{
							const trimmed = item && item.trim()
							if(trimmed){
								collected.add(trimmed)
							}
						})
					}
				}
				if(Array.isArray(this.form.attachments)){
					this.form.attachments.filter(Boolean).forEach(item=>addValue(item))
				}
				addValue(this.form.attachment)
				this.attachmentList = Array.from(collected).map(url=>({
					url,
					name: this.extractFileName(url),
					extname: this.extractExt(url)
				}))
				this.syncAttachmentField()
			},
			updateSignFromData(){
				if(this.form.simplingSign){
					this.samplingSignList = [{ name: this.extractFileName(this.form.simplingSign), url: this.form.simplingSign }]
				}else{
					this.samplingSignList = []
				}
				if(this.form.testedSign){
					this.testedSignList = [{ name: this.extractFileName(this.form.testedSign), url: this.form.testedSign }]
				}else{
					this.testedSignList = []
				}
			},
			async loadDetectionDict(){
				try{
					const res = await request({url:`/system/dict/data/type/${this.detectionTypeDictType}`,method:'get'})
					const rows = Array.isArray(res)?res:(Array.isArray(res?.data)?res.data:[])
					const map={}
					rows.forEach(d=>{const label=d.dictLabel??d.label??d.name;const value=d.dictValue??d.value??d.code;if(value!=null){map[value]=label||value}})
					this.detectionTypeMap=map
				}catch(e){this.detectionTypeMap={}}
			},
			async loadMapKey(){
				if(!this.isH5){
					return
				}
				try{
					const res = await request({ url: '/system/config/configKey/map_key', method: 'get' })
					this.mapKey = res?.msg || res?.data || this.mapKey
				}catch(e){
					this.mapKey = this.mapKey || ''
				}
				this.initTiandituMap()
			},
			initTiandituMap(){
				if(!this.isH5){
					return
				}
				if(typeof window === 'undefined') return
				if(window.T){
					this.initMapInstance()
					return
				}
				if(!this.mapKey){
					return
				}
				this.loadTiandituScript()
			},
			loadTiandituScript(){
				if(typeof document === 'undefined') return
				if(document.getElementById('tianditu-script')){
					return
				}
				const script = document.createElement('script')
				script.id = 'tianditu-script'
				script.type = 'text/javascript'
				script.src = `https://api.tianditu.gov.cn/api?v=4.0&tk=${this.mapKey}`
				script.onload = () => {
					this.initMapInstance()
				}
				script.onerror = () => {
					uni.showToast({ title: '地图加载失败', icon: 'none' })
				}
				document.head.appendChild(script)
			},
			initMapInstance(){
				if(!this.isH5 || typeof window === 'undefined' || !window.T){
					return
				}
				const mapContainer = document.getElementById('tiandituMap')
				if(!mapContainer){
					return
				}
				const initLng = parseFloat(this.form.lng) || this.defaultLng
				const initLat = parseFloat(this.form.lat) || this.defaultLat
				const initPoint = new window.T.LngLat(initLng, initLat)
				this.mapInstance = new window.T.Map('tiandituMap')
				this.mapInstance.centerAndZoom(initPoint, 13)
				this.mapInstance.enableScrollWheelZoom()
				const zoomControl = new window.T.Control.Zoom()
				this.mapInstance.addControl(zoomControl)
				const typeControl = new window.T.Control.MapType()
				this.mapInstance.addControl(typeControl)
				this.mapInstance.addEventListener('dblclick', (e) => {
					const lngLat = e.lnglat
					this.form.lng = Number(lngLat.lng).toFixed(6)
					this.form.lat = Number(lngLat.lat).toFixed(6)
					this.drawMarker(new window.T.LngLat(lngLat.lng, lngLat.lat))
					uni.showToast({ title:'定位成功', icon:'success' })
				})
				this.drawMarker(initPoint)
				this.getCurrentLocation()
			},
			drawMarker(point){
				if(!this.isH5 || typeof window === 'undefined' || !window.T || !this.mapInstance){
					return
				}
				const targetPoint = point instanceof window.T.LngLat ? point : new window.T.LngLat(parseFloat(this.form.lng) || this.defaultLng, parseFloat(this.form.lat) || this.defaultLat)
				if(this.mapMarker){
					this.mapInstance.removeOverLay(this.mapMarker)
				}
				this.mapMarker = new window.T.Marker(targetPoint)
				this.mapInstance.addOverLay(this.mapMarker)
			},
			getCurrentLocation(){
				if(!this.isH5 || typeof navigator === 'undefined' || !navigator.geolocation){
					return
				}
				navigator.geolocation.getCurrentPosition((pos)=>{
					const lng = Number(pos.coords.longitude).toFixed(6)
					const lat = Number(pos.coords.latitude).toFixed(6)
					this.form.lng = lng
					this.form.lat = lat
					if(this.mapInstance && window.T){
						const point = new window.T.LngLat(lng, lat)
						this.mapInstance.centerAndZoom(point, 15)
						this.drawMarker(point)
					}
				},()=>{}, { enableHighAccuracy:true, timeout:8000, maximumAge:600000 })
			},
			async loadDetail() {
				try {
					const res = await trcydetail(this.id)
					console.log(res)
					const d = res?.data || {}
					// 按照后台返回字段映射到表单
					Object.assign(this.form, {
						simplingCode: d.simplingCode || '',
						taskSource: d.taskSource || '',
						monitorType: d.monitorType || '',
						soilType: d.soilType || '',
						irrigationMethod: d.irrigationMethod || d.irrigation || '',
						plantProduct: d.growProduct || d.plantProduct || '',
						growProductPath: [],
						surroundingsData: d.surroundingsData || '',
						monitorPlace: d.monitorPlace || '',
						simplingStandard: d.simplingStandard || '',
						simplingDeep: d.simplingDeep || '',
						sampleWeight: d.sampleWeight || d.sampleWeight || '',
						simplingTime: d.simplingTime || '',
						simplingPlace: d.simplingPlace || '',
						simplingPerson: d.simplingPerson || '',
						lng: d.longitude || d.long || '',
						lat: d.latitude || d.lat || '',
						testedName: d.testedName || '',
						testedType: d.testedType || '',
						contact: d.contact || '',
						contactPhone: d.contactPhone || '',
						testedIdNo: d.testedIdNo || d.testedId || '',
						address: d.address || '',
						simplingRemark: d.simplingRemark || '',
						testedRemark: d.testedRemark || '',
						simplingSign: d.simplingSign || '',
						testedSign: d.testedSign || '',
						attachment: d.attachment || '',
						attachments: d.attachment ? [d.attachment] : (d.attachments || []),
						remark: d.remark || ''
					})
					this.pendingGrowProductValue = d.growProduct || d.plantProduct || ''
					this.applyGrowProductValue()
					this.updateAttachmentFromData()
					this.updateSignFromData()
					if(this.isH5){
						this.$nextTick(()=>{
							this.initMapInstance()
						})
					}
				} catch (e) {
					console.error('加载详情失败', e)
				}
			},
			onDateConfirm(e) {
				this.dateVisible = false
				if (e?.value) {
					const d = new Date(e.value)
					const y = d.getFullYear(),
						m = ('0' + (d.getMonth() + 1)).slice(-2),
						day = ('0' + d.getDate()).slice(-2)
					this.form.simplingTime = `${y}-${m}-${day}`
				}
			},
			onMapPick(p) {
				if (p && p.lng && p.lat) {
					this.form.lng = String(p.lng)
					this.form.lat = String(p.lat)
				}
			},
			onChooseSoilType(){
				const items = this.soilTypeOptions.map(o=>o.label||o.value)
				uni.showActionSheet({
					itemList: items,
					success: (res)=>{
						const idx = res.tapIndex
						if (idx!=null && this.soilTypeOptions[idx]){
							this.form.soilType = this.soilTypeOptions[idx].value
						}
					}
				})
			},
			onChooseTestedType() {
				const items = this.testedTypeOptions
				uni.showActionSheet({
					itemList: items,
					success: (res) => {
						const idx = res.tapIndex
						if (idx != null && items[idx]) {
							this.form.testedType = items[idx]
						}
					}
				})
			},
			// 存草稿
			async onSaveDraft() {
				const payload = this.buildPayload('draft')
				try {
					uni.showLoading({
						title: '保存草稿中...'
					})
					await editcy(payload)
					uni.hideLoading()
					uni.showToast({
						title: '草稿已保存',
						icon: 'success'
					})
					setTimeout(() => uni.navigateBack(), 600)
				} catch (e) {
					uni.hideLoading()
					uni.showToast({
						title: '保存失败',
						icon: 'none'
					})
				}
			},
			
			// 提交
			async onSubmit() {
				// 表单验证
				if (!this.validateForm()) {
					return
				}
				
				// 显示确认框
				uni.showModal({
					title: '确认提交',
					content: '确定提交抽样单？提交后不可再次修改',
					success: async (res) => {
						if (res.confirm) {
							await this.submitForm('commit')
						}
					}
				})
			},
			
			// 构建提交数据
			buildPayload(status) {
				const payload = {
					id: this.id,
					status: status,
					simplingCode: this.form.simplingCode,
					taskSource: this.form.taskSource,
					monitorType: this.form.monitorType,
					soilType: this.form.soilType,
					irrigationMethod: this.form.irrigationMethod,
					growProduct: this.form.plantProduct,
					surroundingsData: this.form.surroundingsData,
					monitorPlace: this.form.monitorPlace,
					simplingStandard: this.form.simplingStandard,
					simplingDeep: this.form.simplingDeep,
					sampleWeight: this.form.sampleWeight ? parseFloat(this.form.sampleWeight) : null,
					simplingTime: this.form.simplingTime,
					simplingPlace: this.form.simplingPlace,
					simplingPerson: this.form.simplingPerson,
					longitude: this.form.lng,
					latitude: this.form.lat,
					testedName: this.form.testedName,
					testedType: this.form.testedType,
					contact: this.form.contact,
					contactPhone: this.form.contactPhone,
					testedIdNo: this.form.testedIdNo,
					address: this.form.address,
					simplingRemark: this.form.simplingRemark,
					testedRemark: this.form.testedRemark,
					simplingSign: this.form.simplingSign,
					testedSign: this.form.testedSign,
					attachment: this.form.attachment || (this.form.attachments && this.form.attachments[0]) || '',
					remark: this.form.remark
				}
				
				// 如果是提交状态，添加任务参数
				if (status === 'commit') {
					payload.params = {
						taskId: this.taskId || this.id
					}
				}
				
				return payload
			},
			
			// 表单验证
			validateForm() {
				const requiredFields = [
					{ field: 'simplingCode', name: '抽样编号' },
					{ field: 'soilType', name: '土壤类型' },
					{ field: 'irrigationMethod', name: '灌溉方式' },
					{ field: 'plantProduct', name: '种植产品' },
					{ field: 'monitorPlace', name: '监测场所' },
					{ field: 'simplingStandard', name: '采样依据' },
					{ field: 'simplingDeep', name: '采样深度' },
					{ field: 'sampleWeight', name: '采样重量' },
					{ field: 'simplingTime', name: '采样时间' },
					{ field: 'simplingPerson', name: '采样人员' },
					{ field: 'testedName', name: '受检单位名称' },
					{ field: 'contact', name: '联系人' },
					{ field: 'contactPhone', name: '联系电话' }
				]
				
				for (let item of requiredFields) {
					if (!this.form[item.field]) {
						uni.showToast({
							title: `请填写${item.name}`,
							icon: 'none'
						})
						return false
					}
				}
				
				// 数值类校验
				if(this.form.sampleWeight && isNaN(Number(this.form.sampleWeight))){
					uni.showToast({ title: '采样重量需为数字', icon: 'none' })
					return false
				}
				const lng = Number(this.form.lng)
				const lat = Number(this.form.lat)
				if(isNaN(lng) || isNaN(lat)){
					uni.showToast({ title: '经纬度需为数字', icon: 'none' })
					return false
				}
				if(lng < -180 || lng > 180 || lat < -90 || lat > 90){
					uni.showToast({ title: '经纬度超出有效范围', icon: 'none' })
					return false
				}
				// 手机号简单校验
				if(this.form.contactPhone && !/^\+?\d[\d\- ]{5,20}$/.test(this.form.contactPhone)){
					uni.showToast({ title: '联系电话格式不正确', icon: 'none' })
					return false
				}
				
				return true
			},
			
			// 提交表单
			async submitForm(status) {
				this.submitLoading = true
				const payload = this.buildPayload(status)
				
				try {
					uni.showLoading({
						title: status === 'draft' ? '保存草稿中...' : '提交中...'
					})
					
					if (status === 'draft') {
						await editcy(payload)
					} else {
						await commitSampling(payload)
					}
					
					uni.hideLoading()
					uni.showToast({
						title: status === 'draft' ? '草稿已保存' : '提交成功',
						icon: 'success'
					})
					
					setTimeout(() => uni.navigateBack(), 600)
				} catch (e) {
					uni.hideLoading()
					uni.showToast({
						title: status === 'draft' ? '保存失败' : '提交失败',
						icon: 'none'
					})
					console.error('提交失败:', e)
				} finally {
					this.submitLoading = false
				}
			},
			onCancel() {
				uni.navigateBack()
			},
			onAttachmentSelect(e){
				const files = e?.tempFiles || []
				files.forEach(async file => {
					if(file?.size && file.size > 10 * 1024 * 1024){
						uni.showToast({ title: '文件不能超过10MB', icon: 'none' })
						return
					}
					const url = await this.doUpload(file)
					if(url){
						this.attachmentList.push({
							name: this.extractFileName(url),
							url,
							extname: this.extractExt(url)
						})
						this.syncAttachmentField()
					}
				})
			},
			onAttachmentDelete(e){
				const index = e?.index
				if(index !== undefined){
					this.attachmentList.splice(index, 1)
					this.syncAttachmentField()
				}
			},
			onSamplingSignSelect(e){
				const files = e?.tempFiles || []
				if(!files.length){
					return
				}
				const file = files[0]
				if(file?.size && file.size > 5 * 1024 * 1024){
					uni.showToast({ title: '图片不能超过5MB', icon: 'none' })
					return
				}
				this.uploadSign(file, 'simpling')
			},
			onSamplingSignDelete(){
				this.samplingSignList = []
				this.form.simplingSign = ''
			},
			onTestedSignSelect(e){
				const files = e?.tempFiles || []
				if(!files.length){
					return
				}
				const file = files[0]
				if(file?.size && file.size > 5 * 1024 * 1024){
					uni.showToast({ title: '图片不能超过5MB', icon: 'none' })
					return
				}
				this.uploadSign(file, 'tested')
			},
			onTestedSignDelete(){
				this.testedSignList = []
				this.form.testedSign = ''
			},
			async uploadSign(file, type){
				const url = await this.doUpload(file)
				if(!url){
					return
				}
				const entry = [{ name: this.extractFileName(url), url }]
				if(type === 'simpling'){
					this.samplingSignList = entry
					this.form.simplingSign = url
				}else{
					this.testedSignList = entry
					this.form.testedSign = url
				}
			},
			async doUpload(file){
				try{
					const filePath = file?.filePath || file?.path || file?.tempFilePath
					if(!filePath){
						return ''
					}
					uni.showLoading({ title: '上传中...' })
					const result = await upload({ url: '/common/upload', filePath, name: 'file' })
					const url = result?.data?.url || result?.data?.path || result?.data || ''
					if(url){
						uni.showToast({ title: '上传成功', icon: 'success' })
					}
					return url
				}catch(e){
					console.error('上传失败', e)
					uni.showToast({ title: '上传失败', icon: 'none' })
					return ''
				}finally{
					uni.hideLoading()
				}
			},
			syncAttachmentField(){
				const urls = this.attachmentList.map(item => item.url).filter(Boolean)
				this.form.attachment = urls.join(',')
				this.form.attachments = urls
			},
			extractFileName(path){
				if(!path) return ''
				const segments = path.split('?')[0].split('/')
				return segments[segments.length - 1] || ''
			},
			extractExt(path){
				const name = this.extractFileName(path)
				const idx = name.lastIndexOf('.')
				return idx > -1 ? name.substring(idx + 1) : ''
			},
			onNativeMapTap(e){
				const { longitude, latitude } = e?.detail || {}
				if(!longitude || !latitude){
					return
				}
				this.form.lng = Number(longitude).toFixed(6)
				this.form.lat = Number(latitude).toFixed(6)
				if(this.isH5 && typeof window !== 'undefined' && window.T && this.mapInstance){
					const point = new window.T.LngLat(this.form.lng, this.form.lat)
					this.drawMarker(point)
				}
			},
			searchLocation(){
				if(!this.form.simplingPlace){
					return uni.showToast({ title: '请输入抽样地点', icon: 'none' })
				}
				if(this.isH5 && typeof window !== 'undefined' && window.T && typeof window.T.Geocoder === 'function'){
					const geocoder = new window.T.Geocoder()
					geocoder.getPoint(this.form.simplingPlace, (res)=>{
						const lng = res?.lnglat?.lng
						const lat = res?.lnglat?.lat
						if(lng && lat){
							this.form.lng = Number(lng).toFixed(6)
							this.form.lat = Number(lat).toFixed(6)
							const point = new window.T.LngLat(this.form.lng, this.form.lat)
							if(this.mapInstance){
								this.mapInstance.centerAndZoom(point, this.mapInstance.getZoom() || 15)
							}
							this.drawMarker(point)
						}else{
							uni.showToast({ title: '未查询到地点', icon: 'none' })
						}
					})
				}else{
					uni.showToast({ title: '当前端不支持地点检索', icon: 'none' })
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	$brand: #1fa144;
	$brand-strong: #138735;
	$brand-weak: #eef9f2;
	$page-bg: #f6f8f7;

	.page {
		min-height: 100vh;
		background: $page-bg;
	}

	.mine-navbar-bg {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		z-index: 1;
		height: 180rpx;
	}

	.scroll {
		height: calc(100vh - 180rpx);
		padding: 24rpx 24rpx 120rpx;
		box-sizing: border-box;
	}

	.card {
		background: #fff;
		border: 1rpx solid #d9f1e2;
		border-radius: 20rpx;
		padding: 26rpx 26rpx 10rpx;
		margin-bottom: 24rpx;
		box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, .04);
	}

	.card-title {
		font-size: 30rpx;
		font-weight: 600;
		color: #0f5132;
		position: relative;
		padding-left: 20rpx;
		margin-bottom: 18rpx;
	}

	.card-title:before {
		content: '';
		position: absolute;
		left: 0;
		top: 8rpx;
		width: 10rpx;
		height: 28rpx;
		background: linear-gradient(180deg, $brand, #62c978);
		border-radius: 6rpx;
	}

	.form-item {
		display: flex;
		flex-direction: column;
		margin-bottom: 24rpx;
	}

	.form-item:last-child {
		margin-bottom: 0;
	}

	.label {
		font-size: 26rpx;
		color: #275134;
		margin-bottom: 10rpx;
	}

	.required>.label:before {
		content: '';
		color: #f0564a;
		margin-right: 6rpx;
	}

	.row-2 {
		display: flex;
		flex-direction: column;
		gap: 16rpx;
	}

	.row-2>.form-item {
		flex: initial;
	}

	.input-with-action {
		display: flex;
		align-items: center;
		gap: 12rpx;
	}

	.input-with-action .action-btn {
		min-width: 140rpx;
		height: 76rpx;
		border-radius: 14rpx;
		background: $brand;
		color: #fff;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 28rpx;
	}

	.picker-box {
		height: 76rpx;
		background: $brand-weak;
		border: 1rpx solid #d2eadb;
		border-radius: 14rpx;
		padding: 0 24rpx;
		display: flex;
		align-items: center;
		color: #0a3c22;
		font-size: 28rpx;
	}

	.map-wrapper {
		height: 300rpx;
		border: 1rpx solid #d2eadb;
		border-radius: 18rpx;
		overflow: hidden;
		margin-bottom: 18rpx;
	}

	.tianditu-map {
		width: 100%;
		height: 100%;
	}

	.map-tip {
		display: flex;
		align-items: center;
		gap: 12rpx;
		margin: 10rpx 0 14rpx;
	}

	.map-tip .tip-icon {
		width: 28rpx;
		height: 28rpx;
		border-radius: 50%;
		background: #d9f1e2;
		color: #0a3c22;
		display: inline-flex;
		align-items: center;
		justify-content: center;
		font-size: 22rpx;
	}

	.map-tip .tip-text {
		font-size: 22rpx;
		color: #2f7650;
	}

	.tip {
		font-size: 22rpx;
		color: #2f7650;
		margin-bottom: 16rpx;
	}

	.footer {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		background: #fff;
		display: flex;
		justify-content: space-between;
		padding: 16rpx 40rpx 30rpx;
		box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, .05);
	}

	.btn {
		height: 76rpx;
		line-height: 76rpx;
		padding: 0 48rpx;
		border-radius: 18rpx;
		font-size: 30rpx;
		font-weight: 600;
	}

	.btn-outline {
		background: $brand-weak;
		color: $brand-strong;
	}

	.btn-secondary {
		background: #f8f9fa;
		color: #6c757d;
		border: 1rpx solid #dee2e6;
	}
	
	.btn-primary {
		background: linear-gradient(90deg, $brand, $brand-strong);
		color: #fff;
		box-shadow: 0 8rpx 18rpx rgba(31, 161, 68, .25);
	}

	.safe-space {
		height: 40rpx;
	}
</style>